import httpRequest from "@/api/httpRequest";

export default {
    state: {
        activeIndex: 0,
        chats: [],
        isAllDataLoaded: false,
        childrenFlag: 0,
        closeChat: false,
        // recordList: []
        num: 0,
        shopnum: 0,
        bhyLastContent: '',
        shopLastContent: '',
        shopChats: [],
        activeShopIdx: 0,
        searchKey: ''
    },
    mutations: {
        setSearchKey(state, keyWord) {
            console.log('state', keyWord)
            state.searchKey = keyWord
        },
        editChats(state, list) {
            state.chats.unshift(list)
            console.log('0000000',state.chats)
        },
        editShopChats(state, list) {
            if(state.shopChats.length<=0){
                state.shopChats.unshift(list)
            }else{
                let findIndex = state.shopChats.findIndex(item=>item.targetId==list.targetId)
                if(findIndex==-1){
                    state.shopChats.unshift(list)
                }
            }
        },
        setRecondList(state, list) {
            state.chats[state.activeIndex].messages = list
        },
        setShopRecondList(state, list) {
            state.shopChats[state.activeShopIdx].messages = list
        },
        addRecondList(state, list) {
            state.chats[state.activeIndex].messages = list.concat(...state.chats[state.activeIndex].messages)
        },
        closeChat(state) {
            state.closeChat = false
        },
        setChildrenFlag(state, Boolean) {
            state.childrenFlag = Boolean
        },
        restChats(state) {
            state.chats = [];
        },
        // initChatStore(state) {
        //     state.chats = [];
        //     //请求好友列表
        //     let query = {
        //         current: 0,
        //         size: 100
        //     }
        //     httpRequest({
        //         url: `/friend/cmsFriends`,
        //         method: 'get',
        //         params: query
        //     }).then((res) => {
        //         res.records = res.records.map(record => {
        //             return {
        //                 ...record,
        //                 messages: [] // 添加 messages 字段，并赋值为空数组
        //             };
        //         });
        //         this.commit("setYaseeList", res.records);
        //     })
        // },
        initShopStore(state) {
            state.shopChats = [];
            //请求好友列表
            let query = {
                current: 0,
                size: 100
            }
            httpRequest({
                url: `/friend/shopFriends`,
                method: 'get',
                params: query
            }).then((res) => {
                res.records = res.records.map(record => {
                    return {
                        ...record,
                        messages: [] // 添加 messages 字段，并赋值为空数组
                    };
                });
                this.commit("setShopList", res.records);
            })
        },
        setYaseeList(state, yaseelist) {
            state.chats = yaseelist;
        },
        setShopList(state, shopList) {
            console.log('shopList',shopList)
            state.shopChats = shopList
        },
        addYaseeList(state, addList) {
            state.chats = [...state.chats, ...addList]
        },
        openChat(state, chatInfo) {
            let chat = null;
            let activeChat = state.activeIndex >= 0 ? state.chats[state.activeIndex] : null;
            for (let i in state.chats) {
                if (state.chats[i].type == chatInfo.type &&
                    state.chats[i].targetId === chatInfo.targetId) {
                    chat = state.chats[i];
                    // 放置头部
                    state.chats.splice(i, 1);
                    // state.chats.unshift(chat);
                    state.chats.splice(1, 0, chat)
                    // state.chats.push(state.chats[1])
                    break;
                }
            }
            // 创建会话
            if (chat == null) {
                chat = {
                    targetId: chatInfo.targetId,
                    type: chatInfo.type,
                    showName: chatInfo.showName,
                    headImage: chatInfo.headImage,
                    lastContent: "",
                    lastSendTime: new Date().getTime(),
                    unreadCount: 0,
                    messages: [],
                };
                state.chats.unshift(chat);
            }
            // 选中会话保持不变
            if (activeChat) {
                state.chats.forEach((chat, idx) => {
                    if (activeChat.type == chat.type
                        && activeChat.targetId == chat.targetId) {
                        state.activeIndex = idx;
                    }
                })
            }
        },
        activeChat(state, idx) {
            console.log('chatStore activeChat', state.chats, idx)
            state.activeIndex = idx;
            state.chats[idx].unreadCount = 0;
        },
        activeShopChat(state, idx) {
            console.log('activeShopChat', idx)
            state.activeShopIdx = idx
            state.shopChats[idx].unreadCount = 0
        },

        activeMessage(state, newReconds) {
            state.chats[state.activeIndex].messages = newReconds
        },
        removeChat(state, idx) {
            state.chats.splice(idx, 1);
            if (state.activeIndex >= state.chats.length) {
                state.activeIndex = state.chats.length - 1;
            }
        },
        removeGroupChat(state, groupId) {
            for (let idx in state.chats) {
                if (state.chats[idx].type == 'GROUP' &&
                    state.chats[idx].targetId == groupId) {
                    this.commit("removeChat", idx);
                }
            }
        },
        removePrivateChat(state, userId) {
            for (let idx in state.chats) {
                if (state.chats[idx].type == 'PRIVATE' &&
                    state.chats[idx].targetId == userId) {
                    this.commit("removeChat", idx);
                }
            }
        },
//         insertReconds(state, msgInfo) {
//             let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
// // 如果是已存在消息，则覆盖旧的消息数据
//             for (let idx in state.recordList) {
//                 if (msgInfo.id && state.recordList[idx].id == msgInfo.id) {
//                     Object.assign(state.recordList[idx], msgInfo);
//                     return;
//                 }
//                 // 正在发送中的消息可能没有id,通过发送时间判断
//                 if (msgInfo.selfSend && state.recordList[idx].selfSend
//                     && state.recordList[idx].sendTime == msgInfo.sendTime) {
//                     Object.assign(state.recordList[idx], msgInfo);
//                     return;
//                 }
//             }
//             // 新的消息
//             state.recordList.push(msgInfo);
//         },
        insertShopMessage(state, msgInfo) {
            if (msgInfo.username == 'yaseeshop') {
                state.shopnum += 1
                if (msgInfo.type == 1) {
                    state.shopLastContent = "[图片]";
                } else if (msgInfo.type == 2) {
                    state.shopLastContent = "[文件]";
                } else if (msgInfo.type == 3) {
                    state.shopLastContent = "[语音]";
                } else {
                    state.shopLastContent = msgInfo.content
                }
            }
            // let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
            let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
            let shopchat = state.shopChats.find(item => {
                return item.targetId === targetId
            });

            // 插入新的数据
            if (msgInfo.type == 1) {
                shopchat.lastContent = "[图片]";
            } else if (msgInfo.type == 2) {
                shopchat.lastContent = "[文件]";
            } else if (msgInfo.type == 3) {
                shopchat.lastContent = "[语音]";
            } else {
                shopchat.lastContent = msgInfo.content;
            }
            shopchat.lastSendTime = msgInfo.sendTime;
            // 如果不是当前会话，未读加1
            shopchat.unreadCount++;
            console.log('selfSend', msgInfo)
            if (msgInfo.selfSend) {
                shopchat.unreadCount = 0;
            }
            // 如果是已存在消息，则覆盖旧的消息数据
            for (let idx in shopchat.messages) {
                if (msgInfo.id && shopchat.messages[idx].id == msgInfo.id) {
                    Object.assign(shopchat.messages[idx], msgInfo);
                    return;
                }
                // 正在发送中的消息可能没有id,通过发送时间判断
                if (msgInfo.selfSend && shopchat.messages[idx].selfSend
                    && shopchat.messages[idx].sendTime == msgInfo.sendTime) {
                    Object.assign(shopchat.messages[idx], msgInfo);
                    return;
                }
            }
            // 新的消息
            shopchat.messages.push(msgInfo);
            // state.chats.splice(state.activeIndex, 1, chat)
            console.log('++++', state.shopChats)
        },
        insertMessage(state, msgInfo) {
            if (msgInfo.username == '雅斯官方客服') {
                state.num += 1
                if (msgInfo.type == 1) {
                    state.bhyLastContent = "[图片]";
                } else if (msgInfo.type == 2) {
                    state.bhyLastContent = "[文件]";
                } else if (msgInfo.type == 3) {
                    state.bhyLastContent = "[语音]";
                } else {
                    state.bhyLastContent = msgInfo.content
                }
            }
            // 获取对方id或群id
            // let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
            let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
            // let chat = null;
            // for (let idx in state.chats) {
            //     if (state.chats[idx].type == type &&
            //         state.chats[idx].targetId === targetId) {
            //         chat = state.chats[idx];
            //         break;
            //     }
            // }
            let chat = state.chats.find((item) => {
                return  item.targetId === targetId
            });
            // 插入新的数据
            if (msgInfo.type == 1) {
                chat.lastContent = "[图片]";
            } else if (msgInfo.type == 2) {
                chat.lastContent = "[文件]";
            } else if (msgInfo.type == 3) {
                chat.lastContent = "[语音]";
            } else {
                chat.lastContent = msgInfo.content;
                // state.bhyLastContent = msgInfo.content;
            }
            chat.lastSendTime = msgInfo.sendTime;
            // 如果不是当前会话，未读加1
            chat.unreadCount++;
            console.log('selfSend', msgInfo)
            if (msgInfo.selfSend) {
                chat.unreadCount = 0;
            }
            // 如果是已存在消息，则覆盖旧的消息数据
            for (let idx in chat.messages) {
                if (msgInfo.id && chat.messages[idx].id == msgInfo.id) {
                    Object.assign(chat.messages[idx], msgInfo);
                    return;
                }
                // 正在发送中的消息可能没有id,通过发送时间判断
                if (msgInfo.selfSend && chat.messages[idx].selfSend
                    && chat.messages[idx].sendTime == msgInfo.sendTime) {
                    Object.assign(chat.messages[idx], msgInfo);
                    return;
                }
            }
            if (chat.messages) {
                chat.messages.push(msgInfo); //新消息
            } else {
                let idx = state.chats.findIndex(item => {
                    return item.targetId === targetId
                })
                state.chats.splice(idx, 1) //最新消息的好友置顶
                state.chats.unshift(chat);
            }
            console.log('++++', state.chats)
        },
        deleteMessage(state, msgInfo) {
            // 获取对方id或群id
            let type = msgInfo.groupId ? 'GROUP' : 'PRIVATE';
            let targetId = msgInfo.groupId ? msgInfo.groupId : msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
            let chat = null;
            for (let idx in state.chats) {
                if (state.chats[idx].type == type &&
                    state.chats[idx].targetId === targetId) {
                    chat = state.chats[idx];
                    break;
                }
            }
            for (let idx in chat.messages) {
                // 已经发送成功的，根据id删除
                if (chat.messages[idx].id && chat.messages[idx].id == msgInfo.id) {
                    chat.messages.splice(idx, 1);
                    break;
                }
                // 正在发送中的消息可能没有id，根据发送时间删除
                if (msgInfo.selfSend && chat.messages[idx].selfSend
                    && chat.messages[idx].sendTime == msgInfo.sendTime) {
                    chat.messages.splice(idx, 1);
                    break;
                }
            }
        },
        updateChatFromFriend(state, friend) {
            for (let i in state.chats) {
                let chat = state.chats[i];
                if (chat.type == 'PRIVATE' && chat.targetId == friend.id) {
                    chat.headImage = friend.headImageThumb;
                    chat.showName = friend.nickName;
                    break;
                }
            }
        },
        updateChatFromGroup(state, group) {
            for (let i in state.chats) {
                let chat = state.chats[i];
                if (chat.type == 'GROUP' && chat.targetId == group.id) {
                    chat.headImage = group.headImageThumb;
                    chat.showName = group.remark;
                    break;
                }
            }
        },
        resetChatStore(state) {
            state.activeIndex = -1;
            state.chats = [];
        },
    },
    actions: {
        loginChat({commit}, userInfo) {
            //登录操作
            let loginForm = {
                userName: userInfo.userName ? userInfo.userName : '',
                password: '123456',
                nickName: userInfo.nickName ? userInfo.nickName : '',
                avatar: userInfo.avatar ? userInfo.avatar : ''
            }
            return new Promise((resolve, reject) => {
                httpRequest({
                    url: "/yaseeLogin",
                    method: 'post',
                    data: loginForm
                })
                    .then((data) => {
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
    }
}
